param (
    [string]$user="",
    [string]$user_pwd=""
)

$DATA_BACKUP_AGENT_HOME = (Get-ChildItem env:DATA_BACKUP_AGENT_HOME).Value
$Location = $DATA_BACKUP_AGENT_HOME + "\DataBackup\ProtectClient\Plugins\GeneralDBPlugin\bin\applications\exchange\ps1_scripts"
Set-Location -Path $Location
[string]$common_file_path = (Get-Location).Path + "\Common.ps1"
[string]$pssession_name = "GetMailDB"
[string]$serverName = "Microsoft Exchange Server"
[string]$server = hostname

# 引用Common.ps1
. $common_file_path

# 建立连接
if (!(NewConnection $User $User_pwd $pssession_name)) {
    return $Result | ConvertTo-Json -Compress -Depth 7
}

try {
    # 获取exchange服务器版本
    # Get exchange server version
    [string]$exchangeFilter = "Name='Microsoft Exchange Server'"
    $getApps = Get-CimInstance -ClassName win32_Product -Filter $exchangeFilter | Select Name,Version
    $version = $getApps.Version

    # 获取exchange服务器名称下的数据库列表（注：可能有问题，-Server并未完全生效，会把“将本服务器作为备服务器的数据库也显示”）
    # Get the list of DB under the exchange server name
    $DBList = @()
    $dbsInServer = Invoke-Command -Session $Session -ScriptBlock {Get-MailboxDatabase -Server $Using:server}
    foreach ($db_detail in $dbsInServer) {
        $db_name = $db_detail.Name + "\" + $server
        # Check the mount status of DB
        $db_copystatus = Invoke-Command -Session $Session -ScriptBlock {Get-MailboxdatabaseCopyStatus -identity $Using:db_name}
        $db_status = $db_copystatus.Status
        # check if it is not recovery DB & is mounted
        # 非恢复数据库，已挂载
        if (!$db_detail.Recovery -and $db_status -eq "Mounted") {
            $DBList += $db_detail.Name
        }
    }

    # 获取公共数据库列表
    # 只有Exchange2010可以创建该数据库
    # Get list of public DB
    $getPublic = Invoke-Command -Session $Session -ScriptBlock {Get-PublicFolderDatabase -Server $Using:server}
    foreach ($db_detail in $getPublic) {
        # Check the mount status of DB
        $temp_db_name = $db_detail.Name
        $db_copystatus = Invoke-Command -Session $Session -ScriptBlock {Get-MailboxdatabaseCopyStatus -identity $Using:temp_db_name}
        $db_status = $db_copystatus.Status
        # 非恢复数据库，已挂载
        # check if it is not recovery DB & is mounted
        if (!$db_detail.Recovery -and $db_status -eq "Mounted") {
            $DBList += $getPublic.Name
        }
    }

    $dbListDetail = @()
    foreach ($db_name in $DBList) {
        $db_property = Invoke-Command -Session $Session -ScriptBlock {Get-MailboxDatabase -identity $Using:db_name |
            Select-Object EdbFilePath, LogFolderPath, LogFilePrefix, Guid}
        # 注：Exchange PowerShell下直接获取的不符合预期，需要加pathname
        $db_edb_path = $db_property.EdbFilePath
        $db_log_path = $db_property.LogFolderPath
        if ($db_edb_path -isnot [string]) {
            $db_edb_path = $db_edb_path.PathName
        }
        if ($db_log_path -isnot [string]) {
            $db_log_path = $db_log_path.PathName
        }
        $db_uuid = $db_property.Guid
        $log_file_prefix = $db_property.LogFilePrefix
        $dbDetail = @{
            version = $version
            server_name = $server
            edb_path = $db_edb_path
            log_path = $db_log_path
            db_name = $db_name
            db_uuid = $db_uuid
            log_file_prefix = $log_file_prefix
            state = "Mounted"
        }
        $dbListDetail += $dbDetail
    }
} catch {
    ClosePSSession $pssession_name
    $Result["ReturnCode"] = "-1"
    $Result["Output"] = "Get Mailbox List Failed"
    return $Result | ConvertTo-Json -Compress -Depth 7
}

ClosePSSession $pssession_name
$Result["ReturnCode"] = "0"
$Result["Output"] = $dbListDetail
return $Result | ConvertTo-Json -Compress -Depth 7